﻿using System;
using System.Collections.Generic;
using System.Linq;

using HelfenHelfen.DataAccess.Entities;
using HelfenHelfen.DataAccess.Interfaces;

namespace HelfenHelfen.DataAccess {
   public class UserDetailDataAccess : IUserDetailDataAccess {
      public void Insert(UserDetail newUser) {
         throw new NotImplementedException();
      }

      public void Update(UserDetail user) {
         using (HelfenHelfenEntities db = new HelfenHelfenEntities()) {
            var obj = (from o in db.UserDetails
                       where o.UserDetailGUID == user.UserDetailGUID
                       select o).FirstOrDefault();
            if (obj != null) {
               obj.Username = user.Username;
               obj.FirstName = user.FirstName;
               obj.Lastname = user.Lastname;
               obj.Street = user.Street;
               obj.PostalCode = user.PostalCode;
               obj.City = user.City;
               obj.CountryCode = user.CountryCode;
               obj.EMail = user.EMail;
               obj.PhoneNo = user.PhoneNo;

               db.SaveChanges();
            }
         }
      }

      public void Delete(Guid userGuid) {
         throw new NotImplementedException();
      }

      public UserDetail Get(Guid userGuid) {
         using (HelfenHelfenEntities db = new HelfenHelfenEntities()) {
            var obj = (from o in db.UserDetails
                       where o.UserDetailGUID == userGuid
                       select o).FirstOrDefault();
            return obj;
         }
      }

      public UserDetail GetOrCreate(Guid userDetailId) {
         var obj = Get(userDetailId);
         if (obj == null) {
            UserDetail user = new UserDetail();
            user.UserDetailGUID = userDetailId;
            user.Username = string.Empty;
            user.FirstName = string.Empty;
            user.Lastname = string.Empty;
            user.Street = string.Empty;
            user.PostalCode = string.Empty;
            user.City = string.Empty;
            user.CountryCode = string.Empty;

            using (HelfenHelfenEntities db = new HelfenHelfenEntities()) {
               db.UserDetails.AddObject(user);
               db.SaveChanges();
            }
         }

         return Get(userDetailId);
      }

      public IEnumerable<UserDetail> SearchByName(string searchText, int count){
         using (HelfenHelfenEntities db = new HelfenHelfenEntities()){
            string st = searchText.ToLower();
            var obj = (from o in db.UserDetails
                       where o.FirstName.ToLower().StartsWith(st) || o.Lastname.ToLower().StartsWith(st)
                       select o).Take(count).ToList();
            return obj;
         }
      }
   }
}
